package com.renhe.utils.baowang;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * 文件工具
 * @author austinChen
 * @Created by austinChen on 2015/12/19 14:17.
 */
public final class FileUtil {

    /**
     * 递归创建多级文件夹
     * @param file
     */
    public static void mkDir(File file){
        if(file.getParentFile().exists()){
            file.mkdir();
        }else{
            mkDir(file.getParentFile());
            file.mkdir();
        }
    }

    /**
     * @param dir 检查文件夹不存在则创建,可递归创建
     */
    public static void mkDir(String dir)
    {
        File file = new File(dir);
        mkDir(file);
    }

    public static String encodeBase64File(String path) throws Exception {

        FileInputStream inputFile=null;
        try {
            File file = new File(path);
            inputFile= new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            return new BASE64Encoder().encode(buffer);
        }
        catch (Exception ex)
        {
            log.error("编码文件出现异常!",ex);
        }
        finally {
            if(inputFile!=null)
                inputFile.close();

        }

        return "";

    }

    /**
     * 将base64字符解码保存文件
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */

    public static void decoderBase64File(String base64Code, String targetPath)
            throws Exception {
        FileOutputStream out=null;
        try {
            byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
            out= new FileOutputStream(targetPath);
            out.write(buffer);
        }
        catch (Exception ex)
        {
            log.error("解码文件出现异常!",ex);
        }
        finally {
            if(out!=null)
                out.close();

        }


    }

    /**
     * @param filePath 文件路径
     * @param content 文件内容
     */
    public static void write(String filePath,String content)
    {
        write(filePath,content,"UTF-8");
    }


    /**
     * @param filePath 文件路径
     * @param content 文件内容
     * @param encoding 编码
     */
    public static void write(String filePath,String content,String encoding)
    {
        log.debug("写文件，路径{}", filePath);
        File tmp = new File(filePath);
        if (tmp.exists()) {
            tmp.delete();
        }
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            OutputStreamWriter osw = new OutputStreamWriter(fos, encoding);
            try {
                osw.write(content);
                osw.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (osw != null)
                    osw.close();
                if (fos != null)
                    fos.close();
            }
        }
        catch (Exception ex)
        {
              log.error("写文件出现异常：",ex);
        }
    }

    /**
     * 日志对象
     */
    private static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * @param resName 资源路径
     * @param clazz 类名
     * @return 读取返回的字符串值
     */
    public static String readResource(String resName, Class clazz) {
       return readResource(resName,clazz,false);
    }

    /**
     * @param resName 资源路径
     * @param clazz 类名
     * @param allowChangeLine 是否保留换行符为\n
     * @return 读取返回的字符串值
     */
    public static String readResource(String resName, Class clazz,boolean allowChangeLine){

        InputStream inputStream = null;
        BufferedReader br = null;
        try {
            inputStream = clazz.getResourceAsStream(resName);
            br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String s = "";
            StringBuffer sb = new StringBuffer();
            while ((s = br.readLine()) != null) {
                if(allowChangeLine)
                  sb.append(s + "\n");
                else
                    sb.append(s);
            }

            log.debug("读取类"+clazz+"下的路径"+resName+"的资源文件的配置文件结果为：{}", sb.toString());
            if(allowChangeLine)
              return sb.toString().substring(0,sb.length()-1);
            else
                return sb.toString();
        } catch (Exception ex) {
            log.error("读取类"+clazz+"下的路径"+resName+"的资源文件出错", ex);
            return "";
        } finally {
            try {
                if (br != null)
                    br.close();
                if (inputStream != null)
                    inputStream.close();
            } catch (Exception ex) {
                log.error("读取类"+clazz+"下的路径"+resName+"的,关闭流出错", ex);
            }
        }

    }

    public static String read(String path) {
        return read(path,"UTF-8");
    }

    /**
     * 读取IO文件
     *
     * @param filePath
     * @return
     */
    public static String read(String filePath, String charSet) {
        try {
            String fileContent;
            final File file = new File(filePath);
            final Long size = file.length();
            byte[] buff = new byte[size.intValue()];
            final FileInputStream fs = new FileInputStream(file);
            fs.read(buff);
            fs.close();
            fileContent = new String(buff, charSet);
            return fileContent;
        } catch (Exception e) {
            log.error("文件"+filePath+"读取异常：", e);
            return "";
        }
    }
    public static byte[] getStreamAsByteArray(InputStream stream) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int nextValue = stream.read();
        while (-1 != nextValue ) {
            byteStream.write(nextValue);
            nextValue = stream.read();
        }
        return byteStream.toByteArray();
    }
}
